<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="admin/common/html/head :: head_Normal(~{::title},~{::link},~{::style})">

<title th:text=${title}></title>

<link rel="stylesheet" th:href="@{/static/admin/assets/js/button/ladda/ladda.min.css}">
<link th:href="@{/static/admin/assets/js/bootstrap/css/bootstrap-table/bootstrap-table.min.css}" rel="stylesheet"/>
<link rel="stylesheet" th:href="@{/static/admin/assets/js/button/ladda/ladda.min.css}">

<style type="text/css">
.select-list ul li{
	list-style-type: none;
	float: left;
}
.timeBut{
    float: left;
    padding-top: 15px
}
.timeBut2{
    float: left;
    padding-top: 10px
}
.leapWin{
	width: 100px;
	height: 50px;
	float: left;
	border: 1px dotted #ccc;
}
.leapWinValid{
	border: 1px solid red;
	color: red;
}
.leapWinCounting{
	font-weight: bold;
	color: red;
}
</style>

</head>

<body id="listbody">

<!-- 右边内容 -->
<div class="wrap-fluid">
    <div class="container-fluid paper-wrap bevel tlbr">
        <!-- 内容 -->
        <div class="content-wrap">
            <!-- 结束内容 -->
            <div class="row">
                <div class="col-sm-12">
                    <!-- 搜索条件 -->

                    <div class="nest" id="inlineClose">
                        <div class="title-alt">
                            <h6 style="color:black;"><b>topk热键不包含已经变热的数据</b></h6>
                            <div class="titleClose">
                                <a class="gone" href="#inlineClose">
                                    <span class="entypo-cancel"></span>
                                </a>
                            </div>
                            <div class="titleToggle">
                                <a class="nav-toggle-alt" href="#search_div">
                                    <span class="entypo-down-open"></span>
                                </a>
                            </div>
                        </div>

                        <div class="body-nest" id="search_div"  style="display: block">
                            <div class="form_left">
                                <form role="form" class="form-inline" id="topkCount_searchForm">
                                    <div class="form-group">
                                        <label class="control-label timeBut2" >所属APP：</label>
                                        <select name="appName" id="apps"  onchange="appNameChanged()" class="form-control">
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label class="control-label timeBut2" >规则key：</label>
                                        <select name="ruleKey" id="rule" class="form-control">
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label class="control-label timeBut" >开始时间：</label>
                                        <div class='input-group date datetimepicker' id='datetimepicker1' style="max-width: 220px" data-date-format="yyyy-mm-dd hh">
                                            <input type='text' class="form-control" name="time" id="time"/>
	                                        <input type='hidden' id="startTime" name="startTime"/>
                                            <span class="input-group-addon">
                                                <span class="glyphicon glyphicon-calendar"></span>
                                            </span>
                                        </div>
                                    </div>
                                    <button onclick="$.table.search(this)" style="display:none;" id="topkBtn" type="button"></button>
                                    <button onclick="showLineChart()"  data-toggle='tooltip' title="仅支持查询该小时，点击曲线图数据点查看topk的热键" class="btn btn-success" type="button"><i class="fa fa-search"></i>&nbsp;搜索</button>
                                	<div class="form-group">
                                        <label class="control-label timeBut2">任意key：</label>
                                        <input type="text" id="monitorKey" class="form-control" style="width: 300px;">
                                    </div>
                                    <button onclick="monitor()" class="btn btn-success" type="button">监控</button>
                                </form>
                            </div>
                        </div>
                    </div>
                    <!-- END搜索条件 -->
                    <!-- 空白页开始-->
                    <div class="nest" id="Blank_PageClose">
                        <div class="title-alt">
							<div id="topkCount_lineChart"><center>暂无数据</center></div>
							<center><b id="tableTime"></b></centber>
                            <table id="dataTable" class="table-striped footable-res footable metro-blue" data-page-size="6"></table>
                        </div>
                    </div>
                </div>
                <!-- 空白页结束 -->
            </div>
            <!-- 结束内容 -->
        </div>
    </div>
</div>
<!-- 结束右边内容 -->


<!-- 历史消息 -->
<div id="leapWindowModel" class="modal fade" tabindex="-1" aria-hidden="false">
	<div class="modal-dialog" style="width:1001px;">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
				<h4 class="modal-title" id="leapKey">调用量实时监控</h4>
			</div>
<!-- 				<div id="leapWindowChart" style="min-width:400px;height:400px"></div> -->
			<form class="form-horizontal form-bordered form-row-stripped" id="broker">
				<div class="form-body">
					<div class="form-group">
						<label class="control-label col-md-3"> key: </label>
				        <div class="col-md-8">
							<div class="form-control-static" id="leapWindowKey"></div>
						</div>
					</div>
					<div class="form-group">
						<label class="control-label col-md-3"> 总时间窗口: </label>
				        <div class="col-md-2">
							<div class="form-control-static" id="intervalInMs"></div>
						</div>
						<label class="control-label col-md-3"> 时间窗口长度: </label>
				        <div class="col-md-2">
							<div class="form-control-static" id="windowLengthInMs"></div>
						</div>
					</div>
					<div class="form-group">
						<label class="control-label col-md-3"> 生存时间: </label>
				        <div class="col-md-2">
							<div class="form-control-static" id="survivalTime"></div>
						</div>
						<label class="control-label col-md-3"> 活跃时间: </label>
				        <div class="col-md-2">
							<div class="form-control-static" id="liveTime"></div>
						</div>
					</div>
					<div class="form-group">
						<label class="control-label col-md-3"> 总调用量: </label>
				        <div class="col-md-2">
							<div class="form-control-static" id="totalCount"></div>
						</div>
						<label class="control-label col-md-3"> 有效调用量: </label>
				        <div class="col-md-2">
							<div class="form-control-static" id="validCount"></div>
						</div>
					</div>
					<div class="form-group">
						<label class="control-label col-md-11" style="text-align:center"> 具体滑动窗口如下: </label>
					</div>
				</div>
				<div id="slidingDiv" style="width:1321px;height:55px;"></div>
			</form>
		</div>
	</div>
</div> <!-- 历史消息结束 -->

<!-- 通用js -->
<div th:include="admin/common/html/js :: onload_js">
   
</div>
<!-- bootstarp 表格 -->
<script th:src="@{/static/admin/assets/js/bootstrap/js/bootstrap-table/bootstrap-table.min.js}" type="text/javascript"></script>
<script th:src="@{/static/admin/assets/js/bootstrap/js/bootstrap-table/locale/bootstrap-table-zh-CN.min.js}" type="text/javascript"></script>
<script th:src="@{/static/admin/assets/js/bootstrap/js/base_list.js}" type="text/javascript"></script>

<!-- 弹窗 -->
<script th:src="@{/static/admin/assets/js/layer/layer.js}" type="text/javascript"></script>
<!-- 遮罩层 -->
<script th:src="@{/static/admin/assets/js/blockUI/jquery.blockUI.js}" type="text/javascript"></script>
<script th:src="@{/static/admin/highcharts/highcharts.js}" type="text/javascript"></script>
<!-- 自定义 js -->
<script th:src="@{/static/admin/common/js/lineChart.js}" type="text/javascript"></script>

<script type="text/javascript">
var first = true;
$(function(){
   $('.datetimepicker').datetimepicker({
        language: 'zh-CN',
        CustomFormat: 'yyyy-mm-dd HH',
        weekStart: 1,
        todayBtn: 1,            //显示当天按钮，点击则选择当天当天时间
        autoclose: 1,           //选完时间自动关闭
        todayHighlight: 1,      //当天时间高亮
        startView: 2,           //从月视图开始，选天
        minView: 1,             //提供选择分钟的视图
        forceParse: 0,
        startDate: new Date(new Date().getTime() - 3 * 24 * 60 * 60 * 1000),
        endDate: new Date(),
        minuteStep: 5           //用于构建小时视图。就是最小的视图是每1分钟可选一次。是以分钟为单位的
    });
    $("#datetimepicker1").datetimepicker("setDate", new Date(new Date().getTime() - 5 * 60 * 1000));

    $.ajax({
        cache : true,
        type : "POST",
        url : "/user/info",
        async : false,
        error : function(XMLHttpRequest){
            $.modal.alertError(XMLHttpRequest.responseJSON.msg);
        },
        success : function(data) {
            var apps = data.appNames;
            for (var i = 0; i < apps.length; i++) {
                $("#apps").append("<option>" + apps[i] + "</option>");
            }
            appNameChanged();
        }
    });
})

    // 下拉框联动
    function appNameChanged() {
        var appName = $('#apps option:selected').val();
        $.getJSON('/rule/appRules?appName='+appName, function (data) {
            $("#rule").empty();
            for (var i = 0; i < data.length; i++) {
                var keyRule = data[i];
                $("#rule").append("<option>" + keyRule.key + "</option>");
            }
            if(first){
            	first = false;
            	showLineChart();
            }
        });
    }

function showLineChart(){
	$("#dataTable").bootstrapTable('removeAll');
	drawLineChart('topkCount', function chartToolTip(chart){
		if(!chart){
			return;
		}
		// 使用grafana click效果
		grafanaClick(chart);
		chart.tooltip = {
			formatter: function () {
				var s = "";
				s += "<table style='background-color:white;' border=1><thead><tr>";
				s += "<td>"+this.x+"</td><td>调用量</td><td>总调用量</td><td>占比</td></tr></thead><tbody>";
				$.each(this.points, function (idx) {
					if (typeof(this.point.options.c) == "undefined"){
						return;
					}
					s += "<tr>";
					s += "<td><font color='"+this.series.color+"'>" + this.series.name + "</font></td>";
					s += "<td>" + this.point.options.c + "</td>";
					s += "<td>" + this.point.options.tc + "</td>";
					s += "<td>" + this.point.options.y + "%</td>";
					s += "</tr>";
				});
				return s;
			},
			backgroundColor: '#FFF',
			useHTML: true,
			shared: true
		};
		// 点击事件
		chart.plotOptions.series.events.click= function(e) {
			$("#tableTime").html($("#time").val()+":"+e.point.category + " "+e.point.series.name+"的热key");
			if(e.point.y == 0){
				$("#startTime").val('');
			} else {
				$("#startTime").val($("#time").val()+":"+e.point.category);
			}
			$("#topkBtn").click();
	    }
		// 获取最新时间，展示table
		if(chart.xAxis.categories && chart.xAxis.categories.length){
			var tm = $("#time").val()+":"+chart.xAxis.categories[chart.xAxis.categories.length - 1];
			$("#tableTime").html(tm + " 的热key");
			$("#startTime").val(tm);
			$("#topkBtn").click();
		}
	});
}
$("[data-toggle='tooltip']").tooltip({container: 'body'});

var options = {
    dataUrl: "/topk/hot",
    search: false,
    showRefresh: false,
    showColumns: false,
    dataColumns: [
        { field: 'key', title: 'key', formatter: function(value, item, index) {
            return "<a href='#'>" + value + "</a>";
        }},
        { field: 'count', title: '调用量'},
        { field: 'countRate', title: '调用量占比', formatter: function(value, item, index) {
            return value + "%";
        }},
        { field: 'liveTimeSecond', title: '存活时间(秒)'}]
};
$.table.oTableInit(options).Init();

var appName = "";
var ruleKey = "";
var key = "";

$('#dataTable').on('click-cell.bs.table',
	function(e, field, value, row, $element) {
		if("key" != field){
			return;
		}
		appName = $("#apps").val();
		ruleKey = $("#rule").val();
		key = value;
		$("#slidingDiv").html("<div class='leapWin'></div><div class='leapWin'></div><div class='leapWin'></div><div class='leapWin'></div><div class='leapWin'></div><div class='leapWin'></div><div class='leapWin'></div><div class='leapWin'></div><div class='leapWin'></div><div class='leapWin'></div>");
		leapWindow();
// 		$("#leapKey").html(value + "的滑动窗口");
		$("#leapWindowModel").modal("show");
		loopShow();
	}
)

    
$('#leapWindowModel').on('hidden.bs.modal', function () {
	loopStop();
});

var loopLeapWindow;
function loopShow(){
	loopLeapWindow = setInterval("leapWindow()", 1000);
}

function loopStop(){
	window.clearInterval(loopLeapWindow);
	needInit = true;
	clearAll();
}

function clearAll(){
   $("#leapWindowKey").empty();
   $("#intervalInMs").empty();
   $("#validCount").empty();
   $("#windowLengthInMs").empty();
   $("#totalCount").empty();
   $("#survivalTime").empty();
   $("#liveTime").empty();
   $("#leapWindowTable").bootstrapTable('removeAll');
}

function monitor(){
	if(!$("#monitorKey").val()){
		return;
	}
	key = $("#monitorKey").val();
	appName = $("#apps").val();
	ruleKey = $("#rule").val();
	$("#slidingDiv").html("<div class='leapWin'></div><div class='leapWin'></div><div class='leapWin'></div><div class='leapWin'></div><div class='leapWin'></div><div class='leapWin'></div><div class='leapWin'></div><div class='leapWin'></div><div class='leapWin'></div><div class='leapWin'></div>");
	leapWindow();
	$("#leapWindowModel").modal("show");
	loopShow();
}

var needInit = true;
function leapWindow(){
	 $.ajax({
         url: "/leap/window",
         type: "POST",
         data:{
        	 appName: appName,
        	 ruleKey: ruleKey,
        	 key: key
         },
         dataType: "json",
         success: function(data){
  		   if(!data || data.status != 200){
 			  clearAll();
 			  return;
 		   }
 	 	   var leapWindowData = data.result;
 		   $("#leapWindowKey").html(key);
 		   $("#intervalInMs").html(leapWindowData.intervalInMs+"ms");
 		   $("#validCount").html(leapWindowData.validCount);
 		   $("#windowLengthInMs").html(leapWindowData.windowLengthInMs+"ms");
 		   $("#totalCount").html(leapWindowData.totalCount);
 		   $("#survivalTime").html(leapWindowData.survivalTime+"s");
 		   $("#liveTime").html(leapWindowData.liveTime+"s");
 		   
 		   // 移除样式
 		   $("#slidingDiv").children().each(function(){
 			   var foundData = false;
 			   for(var i in leapWindowData.windowList){
 				   if($(this).attr("id") == leapWindowData.windowList[i].windowStart){
 					   foundData = true;
 					   break;
 				   }
 			   }
 			   if(!foundData){
 				   $(this).removeClass("leapWinValid").removeClass("leapWinCounting");
 			   }
 		   });
 		   
 		   var append = false;
 		   // 更新现有的
 		   for(var i in leapWindowData.windowList){
 			  var newData = leapWindowData.windowList[i];
 			  var divComp = $('#' + newData.windowStart);
 			  if(divComp.length > 0){
 				$('#' + newData.windowStart+"Count").html("调用量:"+newData.value);
    			  	if(newData.deprecated){
    			  		divComp.removeClass("leapWinValid");
    				}
    				if(!newData.counting){
    					divComp.removeClass("leapWinCounting");
    				}
 			  } else {
 				 	append = true;
 			   		var html = "<div id='"+newData.windowStart+"' class='leapWin";
 			   		if(!newData.deprecated){
 			   			html += " leapWinValid";
 			   		}
 			   		if(newData.counting){
 			   			html += " leapWinCounting";
 			   		}
 			   		html += "'><center>"+newData.windowStartFormated+"</center><center";
 			   		html += " id='"+newData.windowStart+"Count'>调用量:"+newData.value+"</center></div>";
 			   		$("#slidingDiv").append(html);
 			  }
 		   }
 		   
//  		   if(!append){
//  			  for(var i = 0; i < leapWindowData.sampleCount;++i){
// 	 			  $("#slidingDiv").append("<div class='leapWin'></div>");
//  			  }
//  		   }
 		   // 滑动
 		   var divs = $("#slidingDiv").children();
 		   var sliding = divs.length - 10;
 		   if(sliding > 0){
 			  var comp = $("#slidingDiv").children(":eq("+(sliding-1)+")");
 			  comp.prevAll().remove();
 			  comp.animate({
				   'margin-left': (sliding * -100) + 'px'
			  }, 500, function(){ 
				  	$(this).remove();
				  }
			  );
 		   }
         },
         error:function(err){
           console.log(err.statusText);
         }
    });
}
</script>

</body>

</html>